package cn.apotato.server.consumer;

import cn.apotato.common.model.system.SysMenu;
import cn.apotato.modules.redis.service.RedisService;
import cn.apotato.server.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

import static cn.apotato.common.core.constant.SecurityConstants.PERMISSION_REDIS_KEY;

/**
 * 权限消费者
 *
 * @author 胡晓鹏
 * @date 2023/06/02
 */
@Slf4j
@Transactional(rollbackFor = RuntimeException.class)
@Component
public class PermissionConsumer {
    public static final int STOP_COUNT = 10000;

    private final RedisService redisService;
    private final SysMenuService sysMenuService;

    public PermissionConsumer(RedisService redisService, SysMenuService sysMenuService) {
        this.redisService = redisService;
        this.sysMenuService = sysMenuService;
    }

    /**
     * 运行
     */
    @Async
    public void run() {
        int count = 0;
        while (count < STOP_COUNT) {
            log.info("Update permission library ...");
            count = check(count);
            SysMenu sysMenu = redisService.pullMessage(PERMISSION_REDIS_KEY, SysMenu.class);
            if (sysMenu != null) {
                CompletableFuture.runAsync(() -> {
                    sysMenuService.create(sysMenu);
                });
                count = 0;
            }
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 检查
     *
     * @param count 数
     * @return int
     */
    public int check(int count) {
        try {
            // 大于10小于100 休眠30秒
            if (count > 10 && count < 100) {
                // 1分钟
                Thread.sleep(60 * 1000);
            }
            // 大于100小于1000 休眠5分钟
            else if (count > 100 && count < 1000) {
                Thread.sleep(5 * 60 * 1000);
            }
            // 大于100小于1000 休眠10分钟
            else if (count > 1000 && count < STOP_COUNT) {
                Thread.sleep(10 * 60 * 1000);
            } else if (count > STOP_COUNT) {
                count = 0;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        count++;
        return count;
    }
}
